package net.wofly.right.service.impl;

import net.wofly.common.util.CommonStatus;
import net.wofly.common.util.Identities;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.ReceivingAddr;
import net.wofly.right.domain.User;
import net.wofly.right.repository.ReceivingAddrRepository;
import net.wofly.right.service.IReceivingAddrService;
import net.wofly.right.service.IUserService;
import net.wofly.right.util.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;

@Service("iReceivingAddrService")
@Transactional
public class ReceivingAddrServiceImpl implements IReceivingAddrService {
    
    @Autowired
    ReceivingAddrRepository receivingAddrRepository;
    
    @Resource
    IUserService iUserService;
    
    @Override
    public ReceivingAddr save(ReceivingAddr entity) {
        return receivingAddrRepository.save(entity);
    }
    
    @Override
    public void delete(ReceivingAddr entity) {
        receivingAddrRepository.delete(entity);
    }
    
    @Override
    public void delete(String key) {
        receivingAddrRepository.delete(key);
    }
    
    @Override
    public ReceivingAddr findOne(String key) {
        return receivingAddrRepository.findOne(key);
    }
    
    @Override
    public List<ReceivingAddr> save(List<ReceivingAddr> entityList) {
        return (List<ReceivingAddr>) receivingAddrRepository.save(entityList);
    }
    
    @Override
    public List<ReceivingAddr> findByUserID(String userID) {
        return receivingAddrRepository.findByUserID(userID);
    }
    
    @Override
    public Integer countByUserIDAndStatus(String userID, Integer status) {
        return receivingAddrRepository.countByUserIDAndStatus(userID, status);
    }
    
    @Override
    public List<ReceivingAddr> findByUserIDAndStatusOrderByDefaultFlagDesc(String userID, Integer status) {
        return receivingAddrRepository.findByUserIDAndStatusOrderByDefaultFlagDesc(userID, status);
    }
    
    @Override
    public ReturnBean<ReceivingAddr> addReceivingAddr(ReceivingAddr receivingAddr) {
        User user = iUserService.findOne(receivingAddr.getUserID());
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "用户ID不正确");
        }
        
        if (user.getUserType().equals(UserType.单位客户.getValue()) && user.getIsLegal().equals(0)) {
            receivingAddr.setUserID(user.getOrganizationID());
        }
        //检查用户收货地址的条数
        if(countByUserIDAndStatus(receivingAddr.getUserID(),CommonStatus.有效.getValue())>=5){
            return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "用户收货地址不能超过5条");
        }

        receivingAddr.setSelectedRegionStr(setSelectedRegionStr(receivingAddr.getSelectedRegion()));

        receivingAddr.setReceivingAddrID(Identities.uuid2());
        receivingAddr.setStatus(CommonStatus.有效.getValue());
        receivingAddr.setOptUserID(receivingAddr.getUserID());
        receivingAddr.setModifyDate(System.currentTimeMillis());
        return new ReturnBean<ReceivingAddr>(0, "添加成功", save(receivingAddr));
    }
    
    @Override
    public ReturnBean<String> delReceivingAddr(String receivingAddrID) {
        ReceivingAddr receivingAddr = findOne(receivingAddrID);
        if (null == receivingAddr) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE.intValue(), "收货地址ID不正确");
        }
        receivingAddr.setStatus(0);
        save(receivingAddr);
        return new ReturnBean<String>(0, "删除成功");
    }
    
    @Override
    public ReturnBean<List<ReceivingAddr>> getUserReceivingAddr(String userID) {
        User user = iUserService.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "用户ID不正确");
        }
        
        if (user.getIsLegal().equals(0)) {
            userID = user.getOrganizationID();
        }
        
        List<ReceivingAddr> receivingAddrs = findByUserIDAndStatusOrderByDefaultFlagDesc(userID,
                CommonStatus.有效.getValue());
        for (ReceivingAddr receivingAddr : receivingAddrs) {
            if (!StringUtils.isEmpty(receivingAddr.getSelectedRegionStr())) {
                receivingAddr.setSelectedRegion(Arrays.asList(receivingAddr.getSelectedRegionStr().split(",")));
            }
        }
        return new ReturnBean<List<ReceivingAddr>>(0, "获取收货地址成功", receivingAddrs);
    }
    
    @Override
    public ReturnBean<ReceivingAddr> updateReceivingAddr(ReceivingAddr receivingAddr) {
        if (StringUtils.isEmpty(receivingAddr.getReceivingAddrID())) {
            return new ReturnBean<ReceivingAddr>(ResultCode.ERROR_SERVICE.intValue(), "待修改的收货地址ID不能为空");
        }
        
        ReceivingAddr oldReceivingAddr = this.findOne(receivingAddr.getReceivingAddrID());
        oldReceivingAddr.setStatus(0);
        save(oldReceivingAddr);
        
        receivingAddr.setReceivingAddrID(Identities.uuid2());
        receivingAddr.setSelectedRegionStr(setSelectedRegionStr(receivingAddr.getSelectedRegion()));
        save(receivingAddr);
        
        return new ReturnBean<ReceivingAddr>(0, "修改收货地址成功", receivingAddr);
    }

    public String setSelectedRegionStr(List<String> selectedRegion){
        String selectedRegionStr = "";
        if (selectedRegion != null && selectedRegion.size() > 0) {
            for (String str : selectedRegion) {
                selectedRegionStr += str + ",";
            }
            selectedRegionStr = selectedRegionStr.substring(0, selectedRegionStr.length() - 1);
        }
        return selectedRegionStr;
    }

	@Override
	public ReturnBean<ReceivingAddr> setDefaultReceivingAddr(String receivingAddrID, Integer defaultFlag) {
		ReceivingAddr receivingAddr = this.findOne(receivingAddrID) ;
		
		if (null == receivingAddr) {
			return new ReturnBean<ReceivingAddr>(ResultCode.ERROR_SERVICE.intValue(), "待修改的收货地址ID不存在！");
		}
		
		if (!defaultFlag.equals(1) && !defaultFlag.equals(0)) {
			return new ReturnBean<ReceivingAddr>(ResultCode.ERROR_SERVICE.intValue(), "设置收货地址默认标志值不正确。只能为1或0！");
		}
		
		if (defaultFlag.equals(1)) {
			List<ReceivingAddr> receivingAddrs = receivingAddrRepository.findByUserIDAndDefaultFlagAndStatus(receivingAddr.getUserID(), 1,1) ;
			for(ReceivingAddr ra :receivingAddrs) {
				ra.setDefaultFlag(0);
			}
			
			this.save(receivingAddrs) ;
		}
		
		receivingAddr.setDefaultFlag(defaultFlag);
		
		this.save(receivingAddr) ;
		
		return new ReturnBean<ReceivingAddr>(0, "修改收货地址成功", receivingAddr);
	}
}
